package com.ezjie.ielts.module_word;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.model.ReviewGroupBean;
import com.ezjie.ielts.model.ReviewGroupResponse;
import com.ezjie.ielts.model.WordGroup;
import com.ezjie.ielts.module_word.adapter.ReviewDetailAdapter;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.DateUtil;
import com.ezjie.ielts.util.DensityUtil;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.PreferencesUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.widget.CustomDialog;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

@ContentView(R.layout.layout_review_detail)
public class ReviewDetailActivity extends BaseFragmentActivity {

	private Context mContext;
	private ReviewDetailAdapter mReviewDetailAdapter;
	private List<WordGroup> mWordGroup;

	@ViewInject(R.id.city_view_pager)
	private ViewPager mViewPager;// 选择词组滑动卡片
	@ViewInject(R.id.pager_ll)
	private LinearLayout pager_ll;
	@ViewInject(R.id.choose_review)
	private TextView choose_review;
	@ViewInject(R.id.iv_topbar_back)
	private ImageView backBtn;
	@ViewInject(R.id.tv_topbar_title)
	private TextView navi_title_text;
	@ViewInject(R.id.page_num)
	private TextView pageNum;
	@ViewInject(R.id.word_img)
	private ImageView word_img;// 问号

	private ReviewGroupBean mReviewGroupBean;
	private int currentIndex = 0;

	private int isReview = 1;// 判断是强化还是复习--0为复习，1为强化

	private WordTask mWordTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		ViewUtils.inject(this);
		mContext = this;
		mWordTask = new WordTask(this);

		init();
	}

	private void init() {
		initView();
		Bundle bundle = getIntent().getExtras();
		isReview = bundle.getInt("type", 0);
		PreferencesUtil.putInt(mContext, "isReview", isReview);
		if (0 == isReview) {
			getReviewGroup("review");
		} else if (1 == isReview) {
			getReviewGroup("strengthen");
		}
		setView();
	}

	private void setView() {

		if (0 == isReview) {
			navi_title_text.setText(R.string.choose_review_title);
			choose_review.setText(R.string.choose_review);
		} else if (1 == isReview) {
			navi_title_text.setText(R.string.choose_strengthen_title);
			choose_review.setText(R.string.choose_strengthen);
		}
		backBtn.setOnClickListener(this);
		word_img.setOnClickListener(this);

		mReviewDetailAdapter = new ReviewDetailAdapter(getSupportFragmentManager());
		mReviewDetailAdapter.setTitles(mWordGroup, isReview);
		mViewPager.setAdapter(mReviewDetailAdapter);
		// mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
		mViewPager.setPageMargin(40);
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				currentIndex = arg0;
				boolean smoothScroll = true;
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						PreferencesUtil.putString(mContext, "temp_status", mWordGroup.get(currentIndex)
								.getTemp_status() + "");
						PreferencesUtil.putInt(mContext, "finish_num", mWordGroup.get(currentIndex).getPassed());
					}
				}, 2000);
				pageNum.setText((currentIndex + 1) + "/" + mWordGroup.size());

				PreferencesUtil.putInt(mContext, "status", mWordGroup.get(currentIndex).getStatus());
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if (pager_ll != null) {
					pager_ll.invalidate();
				}
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	private void initView() {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(mContext, 284),
				LinearLayout.LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.CENTER;
		mViewPager.setLayoutParams(params);
		mWordGroup = new ArrayList<WordGroup>();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_REVIEW_DETAIL);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_REVIEW_DETAIL);
		
		if (mReviewDetailAdapter != null && mWordGroup != null && mWordGroup.size() > 0
				&& mWordGroup.size() >= currentIndex) {
			int temp_status = Integer.parseInt(PreferencesUtil.getString(mContext, "temp_status", "1"));
			int finish_num = PreferencesUtil.getInt(mContext, "finish_num", 0);
			LogUtils.d("summer", currentIndex + "--" + temp_status + "--" + finish_num);
			mWordGroup.get(currentIndex).setPassed(finish_num);
			mWordGroup.get(currentIndex).setTemp_status(temp_status);
			mReviewDetailAdapter.setTitles(mWordGroup, isReview);
			mReviewDetailAdapter.notifyDataSetChanged();
		}
	}

	private void showHintDialog() {
		final CustomDialog dialog = new CustomDialog(mContext, R.layout.layout_review_wenhao_dialog,
				R.style.customDialog);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();

		Button btn_yes = (Button) dialog.findViewById(R.id.btn_yes);
		btn_yes.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
			}
		});
	}

	// 获取单词组
	private void getReviewGroup(String type) {
		if (!NetworkUtil.isNetworkAvailable(mContext)) {
			AppUtil.showToast(mContext, R.string.no_network);
			return;
		}

		mWordTask.getReviewGroup("today", type, DateUtil.getLocalTimeZone(), new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				try {
					ReviewGroupResponse mReviewGroupResponse = JSON.parseObject(result, ReviewGroupResponse.class);
					if (mReviewGroupResponse != null && 200 == mReviewGroupResponse.getStatus_code()) {
						String mGroupBeanStr = mReviewGroupResponse.getData();
						if (!TextUtils.isEmpty(mGroupBeanStr)) {
							mReviewGroupBean = JSON.parseObject(mGroupBeanStr, ReviewGroupBean.class);
							PreferencesUtil.putString(mContext, "mGroupBeanStr", mGroupBeanStr);
							showData(mReviewGroupBean);
						}
					} else {
						AppUtil.showToast(mContext, R.string.load_net_data_failure);
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			private void showData(ReviewGroupBean mReviewGroupBean) {
				if (mReviewGroupBean != null) {
					mReviewDetailAdapter = new ReviewDetailAdapter(getSupportFragmentManager());
					mWordGroup = mReviewGroupBean.getW_groups();
					pageNum.setText(1 + "/" + mWordGroup.size());
					if (mWordGroup.size() > 0) {
						if ((currentIndex + 1) == mWordGroup.size()) {
							PreferencesUtil.putInt(mContext, "nextWgid", -1);
						} else {
							PreferencesUtil.putInt(mContext, "nextWgid", mWordGroup.get(currentIndex + 1).getWgid());
						}
					} else {
						PreferencesUtil.putInt(mContext, "nextWgid", -1);
					}

					if (mWordGroup != null && mWordGroup.size() > currentIndex) {
						PreferencesUtil.putInt(mContext, "status", mWordGroup.get(currentIndex).getStatus());
					}
					mReviewDetailAdapter.setTitles(mWordGroup, isReview);
					mViewPager.setAdapter(mReviewDetailAdapter);
					for (int i = 0; i < mWordGroup.size(); i++) {
						if (mWordGroup.get(i).getTemp_status() != 2) {
							mViewPager.setCurrentItem(i);
							break;
						}
					}
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(mContext, R.string.load_net_data_failure);
			}
		});
	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.iv_topbar_back:
			finish();
			break;
		case R.id.word_img:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "word_review_point");
			showHintDialog();
			break;
		}
	}

}
